package org.community.detail.service.detail.userInfo;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.community.detail.repository.dao.User;
import org.community.detail.repository.dao.UserExample;
import org.community.detail.repository.dao.Visitor;
import org.community.detail.repository.dao.VisitorExample;
import org.community.detail.repository.mappers.UserMapper;
import org.community.detail.repository.mappers.VisitorMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Data
@Slf4j
@Transactional(
        isolation = Isolation.REPEATABLE_READ
)
public class DataBaseService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private VisitorMapper visitorMapper;



    //更新数据库中的用户信息，如果更新成功，就返回用户名
    public String updateUserInfoInDB(Map<String, User> userMap){
        String updateUserName = null;
        int code1 =0 , code2 = 0;
        for(Map.Entry<String,User> entry: userMap.entrySet()){
             code1 = this.getVisitorMapper().updateByPrimaryKeySelective(new Visitor(entry.getValue().getUserId(),entry.getKey(),null));
             code2 = this.getUserMapper().updateByPrimaryKeySelective(entry.getValue());


            updateUserName = entry.getKey();
        }

        if(code1 != 0 && code2 != 0){
            return updateUserName;
        }

        return null;
    }

    //查询用户在数据库中的信息
    public Map<String,User> getUserInfoFromDB(Integer userId){
        User user = this.getUserMapper().selectByPrimaryKey(userId);
        String username = this.getVisitorMapper().selectByPrimaryKey(userId).getUserName();
        Map<String,User> userMap = new HashMap<>();
        userMap.put(username,user);
        return userMap;
    }



    //查询username是否已经存在
    public boolean isUsernameExist(String username){
        VisitorExample example = new VisitorExample();
        example.createCriteria().andUserNameEqualTo(username);
        int count = this.getVisitorMapper().countByExample(example);
        return count != 0;
    }

    //查询username是否与原来的相同
    public boolean isUsernameUpdated(String username,Integer userId){
        VisitorExample example = new VisitorExample();
        example.createCriteria().andUserNameEqualTo(username).andUserIdEqualTo(userId);
        int count = this.getVisitorMapper().countByExample(example);
        return count != 0;
    }

    //查询Id是否存在
    public boolean isIdExist(Integer userId){
        log.info("isIdExist开始执行");
        VisitorExample example = new VisitorExample();
        example.createCriteria().andUserIdEqualTo(userId);
        int count = this.getVisitorMapper().countByExample(example);
        log.info("查找结果：{}",count);
        return this.getVisitorMapper().countByExample(example) != 0;
    }


}
